package ldh.im.fxbase.dao;

import ldh.im.fxbase.data.pojo.ImSetting;
import ldh.im.fxbase.util.DbUtil;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ImSettingDao extends BaseDao {

    private static final String TABLE_NAME = "im_setting";

    public ImSetting getImSettingByUserIdAndName(String userId, String name) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select * from im_setting where name = ? and currentUserId = ?");
            ImSetting imSetting = queryRunner.query(connection, sql, new BeanHandler<ImSetting>(ImSetting.class), name, userId);
            return imSetting;
        });
    }

    public List<ImSetting> getImSettings() throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("select * from im_setting");
            return queryRunner.query(connection, sql, new BeanListHandler<ImSetting>(ImSetting.class));
        });
    }

    public void insertImSetting(ImSetting imSetting) throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            ResultSetHandler<Long> resultSetHandler = new ScalarHandler();
            String sql = String.format("insert into im_setting(name, currentUserId, \"value\", description, ext1, ext2, createTime, updateTime) values(?, ?, ?, ?, ?, ?, ?, ?)");
            Long id = queryRunner.insert(connection, sql, resultSetHandler, imSetting.getName(), imSetting.getCurrentUserId(), imSetting.getValue(), imSetting.getDescription(),
                    imSetting.getExt1(), imSetting.getExt2(), imSetting.getCreateTime(), imSetting.getUpdateTime());
            imSetting.setId(id);
            return imSetting;
        });
    }

    public void updateImSetting(ImSetting imSetting) throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            String sql = String.format("update im_setting set \"value\" = ?, description = ?, ext1 = ?, ext2 = ?, updateTime = ? where name = ? and currentUserId = ?");
            queryRunner.update(connection, sql, imSetting.getValue(), imSetting.getDescription(), imSetting.getExt1(),
                    imSetting.getExt2(), imSetting.getUpdateTime(), imSetting.getName(), imSetting.getCurrentUserId());
            return imSetting;
        });
    }
}
